package com.eds.controller;


import com.eds.pojo.BaseResult;
import com.eds.pojo.CaptchaVerifyRequest;
import com.eds.pojo.CodeEnum;
import com.eds.service.CaptchaService;
import com.eds.utils.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    /* *
     * @Title: generateCaptcha
     * @Author: vvSmile
     * @Date: 2025-03-27 15:30:04
     * @param id 通过 URL 参数传递的标识符，用于区分不同的验证码（如用户会话 ID）。
     * @param response  HTTP 响应对象，用于将验证码图片写入响应体。
     * @Description: TODO 生成验证码接口
     */
    @GetMapping("/generate")
    public void generateCaptcha(@RequestParam String id, HttpServletResponse response) throws IOException {
        // 生成验证码并保存
        CaptchaUtils.Captcha captcha = captchaService.generateCaptcha(id);
        // 设置响应内容类型为PNG图片
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        //设置响应头控制缓存（禁用缓存）
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        //创建字节输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //将生成的图像写入输出流，使用 ImageIO 将生成的验证码图片转换为字节数组，并写入 HTTP 响应输出流
        ImageIO.write(captcha.getImage(), "PNG", outputStream);
        //将图像数据写入响应输出流
        response.getOutputStream().write(outputStream.toByteArray());
    }

    @PostMapping("/verify")
    public BaseResult verifyCaptcha(@RequestBody CaptchaVerifyRequest request) {
        boolean isValid = captchaService.verifyCaptcha(request.getId(), request.getCode());
        if (!isValid) {
            return BaseResult.error(CodeEnum.CAPTCHA_VERIFY_ERROR);
        } else {
            return BaseResult.ok("验证成功");
        }
    }
}